package main;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;

import math.Vector2D;

import entity.Entity;
import entity.building.Building;
import entity.units.Unit;

public class MiniMap
{
	private GameList gL;
	
	private Vector2D posOnScreen;
	
	private int width, height;
	
	private Screen view;
	
	//private Image terrain;
	
	public MiniMap( GameList gL, Vector2D posOnScreen, Screen view, int width, int height )
	{
		this.gL = gL;
		
		this.posOnScreen = posOnScreen;
		
		this.width = width;
		this.height = height;
		
		this.view = view;
	}
	
	public boolean mouseInMiniMap( Vector2D v )
	{
		return (new Rectangle( (int)posOnScreen.getX(), (int)posOnScreen.getY(), width, height )).contains( v.getX(), v.getY() );
	}
	
	public void render( Graphics2D g )
	{
		g.setTransform( AffineTransform.getTranslateInstance( posOnScreen.getX(), posOnScreen.getY() ) );
		
		g.setColor( Color.blue );
		
		for( Entity e : gL.getList() )
		{
			if( e instanceof Building )
			{
				Vector2D pos = fromWorldtoMiniMap( e.getPosition() );
				
				g.fillRect( (int)pos.getX() - 1, (int)pos.getY() - 1, 2, 2 );
			}
			else if( e instanceof Unit )
			{
				Vector2D pos = fromWorldtoMiniMap( e.getPosition() );

				g.fillOval( (int)pos.getX() - 1, (int)pos.getY() - 1, 2, 2 );
			}
		}
		
		Vector2D pos = fromWorldtoMiniMap( view.getPosition() );
		Vector2D dim = fromWorldtoMiniMap( view.getDimensions() );
		
		g.setColor( Color.WHITE );
		
		g.drawRect( (int)pos.getX(), (int)pos.getY(), (int)dim.getX(), (int)dim.getY() );
		g.drawRect( 0, 0, width, height );
		
		g.setTransform( AffineTransform.getTranslateInstance( 0, 0 ) );
	}
	
	public Vector2D fromWorldtoMiniMap( Vector2D v )
	{
		double x = ( v.getX() - v.getX() % 32 + 16 ) / 32;
        double y = ( v.getY() - v.getY() % 32 + 16 ) / 32;

        return new Vector2D( x, y );
	}
	
	/**
	 * This subtracts the position of the minimap on screen from the vector. pass in the mouse point itself.
	 * 
	 * @param v the mouse click on the minimap
	 * @return the point in world coordinates
	 */
	public Vector2D fromMiniMaptoWorld( Vector2D v )
	{
		v.subtract( posOnScreen );
		
		double x = v.getX() * 32 + 16;
		double y = v.getY() * 32 + 16;
    
		return new Vector2D( x, y );
	}
}
